package utility_task

import (
	"Sailor/app/Sailor-console-server/internal/consts"
	"Sailor/app/Sailor-console-server/internal/dao"
	"Sailor/app/Sailor-console-server/internal/model/do"
	"Sailor/app/Sailor-console-server/internal/model/entity"
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/google/uuid"
)

type SysTaskLogService struct {
}

var SysTaskLogServiceApp = new(SysTaskLogService)

// CreateTaskLogByTask 根据sysTask创建任务日志
func (sysTaskLogService *SysTaskLogService) CreateTaskLogByTask(ctx context.Context, sysTask entity.SysTask, status int) (insertId string, err error) {
	uid, _ := uuid.NewV7()
	_, err = dao.SysTaskLog.Ctx(ctx).Insert(do.SysTaskLog{
		Uuid:             uid.String(),
		TaskUuid:         sysTask.Uuid,
		TaskName:         sysTask.TaskName,
		TaskCron:         sysTask.TaskCron,
		TaskInvokeTarget: sysTask.TaskInvokeTarget,
		TaskTimeout:      sysTask.TaskTimeout,
		TaskStartTime:    gtime.Now(),
		TaskEndTime:      gtime.Now(),
		TaskStatus:       status,
	})
	if err != nil {
		g.Log().Error(ctx, "创建任务日志失败", err)
		return "", err
	}
	return uid.String(), err
}

// UpdateTaskLogByTaskResult 更新任务日志
func (sysTaskLogService *SysTaskLogService) UpdateTaskLogByTaskResult(ctx context.Context, taskLogId string, taskResult SysTaskResult) (int64, error) {
	var status int
	result := taskResult.Result
	if taskResult.Err != nil {
		status = consts.Failure
	} else {
		status = consts.Finish
	}

	update, err := dao.SysTaskLog.Ctx(ctx).Where(dao.SysTaskLog.Columns().Uuid, taskLogId).Update(do.SysTaskLog{
		TaskRetryTimes: taskResult.SysTaskLog.TaskRetryTimes,
		TaskStatus:     status,
		TaskResult:     result,
		TaskEndTime:    gtime.Now(),
		TaskTotalTime:  gtime.Now().Sub(taskResult.SysTaskLog.TaskStartTime).Seconds(),
	})
	if err != nil {
		return 0, err
	}
	affected, err := update.RowsAffected()
	if err != nil {
		return 0, err
	}
	// 返回影响的行数
	return affected, nil
}
